<?php
// +----------------------------------------------------------------------
// | 海豚PHP框架 [ DolphinPHP ]
// +----------------------------------------------------------------------
// | 版权所有 2016~2019 广东卓锐软件有限公司 [ http://www.zrthink.com ]
// +----------------------------------------------------------------------
// | 官方网站: http://dolphinphp.com
// +----------------------------------------------------------------------

namespace app\index\controller;

use app\common\controller\Common;
use think\Cache;
use think\facade\Env;
use think\Request;
use think\Db;
/**
 * 前台公共控制器
 * @package app\index\controller
 */
class Home extends Common
{
    //用户 id
    protected $userId = 0;

    //用户
    protected $user;

    protected $request;

    protected $device;

    protected $wxapp_id;
    /**
     * 初始化方法
     * @author 蔡伟明 <314013107@qq.com>
     */
    protected function initialize()
    {
        // 系统开关
        if (!config('web_site_status')) {
            $this->error('站点已经关闭，请稍后访问~');
        }
        $this->_initUser();
    }

    public function __construct()
    {
        $options = [
            // 缓存类型为File
            'type'  =>  'File', 
            // 缓存有效期为永久有效
            'expire'=>  0, 
            //缓存前缀
            'prefix'=>  'think',
             // 指定缓存目录
            'path'  =>  Env::get('root_path').'runtime/cache/',
        ];
        \Cache::connect($options);
        $this->request = \Request::instance();
        $this->_initUser();
    }

    private function _initUser()
    {
        // $token      = $this->request->header('token');
        $token      = $this->request->header('token');
        $device      = $this->request->header('XX-Device-Type');
        $wxapp_id      = $this->request->header('wxapp-id');
        $this->wxapp_id  =  $wxapp_id;
        $this->token = $token;
        
        if (empty($token)) {
            return;
        }
        $userinfo = \Cache::get($token);
        if(!$userinfo){
            //登录失效
            return ;
        }else{
            \Cache::set($token,$userinfo,1800);
        }
        $userinfo = json_decode($userinfo,true);
        $this->user = $userinfo;
        $this->userId = $userinfo['user_id'];
    }

    public function checkLogin()
    {
        if(!$this->userId){
            echo json_encode(['code'=>'-10010','msg'=>'登录失效']);
            exit;
        }
    }
    protected function returnJson($code=10001,$msg="请求成功",$data=[],$request=[])
    {
        $data = [
            'code'=>$code,
            'msg'=>$msg,
            'request'=>$request,
            'data'=>$data
        ];
        exit(json_encode($data));
    }

    protected function getImage($atta_id)
    {
        $path = Db::name('admin_attachment')->where(['id'=>$atta_id,'status'=>1])->value('path');
        if($path){
            $image = config('base_url').'/'.$path;
        }else{
            $image = '';
        }
        return $image;
    }
}
